package com.iyue.sso.helper;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iyue.servlet.taglibs.Functions;

public class CookieUtil {

	/*
	 * Cookie名
	 */
	public static final String COOKIE_AUTH = "iyueba";
	/*
	 * PATH
	 */
	public static final String PATH_ROOT = "/";
	/*
	 * 生存时间
	 */
	public static final int EXPIRE_TIME = 7 * 24 * 60 * 60;
	/*
	 * 域名列表
	 */
	private static List<String> DOMAINS = new ArrayList<String>();

	static {
		DOMAINS.add(null);
		DOMAINS.add("wap.iyueba.com");
		DOMAINS.add("iyueba.com");
//		DOMAINS.add("m.t.10086.cn");
//		DOMAINS.add("wap.t.10086.cn");
//		DOMAINS.add("m.migua.net");
	}

	/**
	 * 设置cookie
	 * 
	 * @param response
	 * @param domain
	 * @param path
	 * @param time
	 * @param name
	 * @param value
	 */
	private static void setCookie(HttpServletResponse response, String domain,
			String path, int time, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(time);
		if (path != null) {
			cookie.setPath(path);
		}
		if (domain != null) {
			cookie.setDomain(domain);
		}

		response.addCookie(cookie);
	}

	/**
	 * 获取cookie
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	private static String getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			return null;
		}

		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				return cookie.getValue();
			}
		}

		return null;
	}

	/**
	 * 设置认证串到cookie
	 * 
	 * @param response
	 * @param value
	 */
	public static void setAuth(HttpServletResponse response, String value) {
		value = Functions.encode(value);
		for (String domain : DOMAINS) {
			setCookie(response, domain, PATH_ROOT, EXPIRE_TIME, COOKIE_AUTH,
					value);
		}
	}

	/**
	 * 清空权限cookie
	 * 
	 * @param request
	 * @param response
	 */
	public static void clearAuth(HttpServletResponse response) {
		for (String domain : DOMAINS) {
			setCookie(response, domain, PATH_ROOT, 0, COOKIE_AUTH, null);
		}
	}

	/**
	 * 从cookie获取认证串
	 * 
	 * @param request
	 * @return
	 */
	public static String getAuth(HttpServletRequest request) {
		return Functions.decode(getCookie(request, COOKIE_AUTH));
	}

}
